package com.penghaisoft.microwms.product.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.ProBarcode;
import com.penghaisoft.microwms.common.data.model.ProHandOutSn;
import com.penghaisoft.microwms.common.data.model.ProSellOutSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.ProCountingDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProCountingDifference;
import com.penghaisoft.microwms.common.wms.model.ProCountingRecords;
import com.penghaisoft.microwms.common.wms.model.ProCountingTask;
import com.penghaisoft.microwms.common.wms.model.ProOrderInSn;
import com.penghaisoft.microwms.common.wms.model.ProScrapOutSn;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.product.dao.ProBarcodeMapper;
import com.penghaisoft.microwms.product.dao.ProCountingDifferenceMapper;
import com.penghaisoft.microwms.product.dao.ProCountingRecordsMapper;
import com.penghaisoft.microwms.product.dao.ProCountingTaskMapper;
import com.penghaisoft.microwms.product.dao.ProHandOutSnMapper;
import com.penghaisoft.microwms.product.dao.ProOrderInSnMapper;
import com.penghaisoft.microwms.product.dao.ProScrapOutSnMapper;
import com.penghaisoft.microwms.product.dao.ProSellOutSnMapper;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.product.service.IProCountingTaskService;

/**
 * <p>
 * 业务逻辑实现类
 * </p>
 * 
 * @author
 * @createDate
 **/
@Service("proCountingTaskService")
public class ProCountingTaskServiceImpl extends BaseService implements IProCountingTaskService {
	@Resource
	private ProCountingTaskMapper proCountingTaskMapper;
	
	@Autowired
	private ProCountingRecordsMapper proCountingRecordsMapper;
	
	@Autowired
	private ProCountingDifferenceMapper proCountingDifferenceMapper;
	
	@Autowired
	private ProHandOutSnMapper proHandOutSnMapper;
	
	@Autowired
	private ProSellOutSnMapper proSellOutSnMapper;
	
	@Autowired
	private ProScrapOutSnMapper proScrapOutSnMapper;
	
	@Autowired
	private ProOrderInSnMapper proOrderInSnMapper;

	@Autowired
	private ProBarcodeMapper proBarcodeMapper;
	
	@Autowired
	private ProStorageSnMapper proStorageSnMapper;
	
	/**
	 * 新增记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp create(ProCountingTask proCountingTask) {
		proCountingTaskMapper.create(proCountingTask);
		return success();
	}

	/**
	 * 删除记录（逻辑删除）
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp delete(ProCountingTask proCountingTask) {
		proCountingTaskMapper.delete(proCountingTask);
		return success();
	}

	/**
	 * 查询列表
	 * 
	 * @param pager
	 * @param baseResource
	 * @return
	 */
	@Override
	public Pager<ProCountingTask> findListByCondition(int page, int rows, ProCountingTask condition) {
		Pager<ProCountingTask> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		List<ProCountingTask> records = proCountingTaskMapper.queryList(pager, condition);
		long size = proCountingTaskMapper.queryCount(condition);
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public ProCountingTask findById(String id) {
		return proCountingTaskMapper.queryById(id);
	}

	/**
	 * 修改记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp update(ProCountingTask proCountingTask) {
		Integer updateCnt = proCountingTaskMapper.updateBySelect(proCountingTask);
		if (updateCnt.intValue() == 1) {
			return success();
		} else {
			return fail("更改状态失败");
		}
	}

	@Override
	public List<ProCountingTask> queryByAny(ProCountingTask proCountingTask) {

		return proCountingTaskMapper.queryByAny(proCountingTask);
	}

	/**
	 * @Title: updateProCountingTask
	 * @Description: 将盘点任务状态置为盘点中
	 * @author jzh
	 * @date 2018年6月13日 上午10:30:58
	 */
	@Override
	public Resp updateProCountingTask(ProCountingTask proCountingTask) {
		proCountingTask.setStauts("1");
		Integer updateCnt = proCountingTaskMapper.update(proCountingTask);
		if (updateCnt.intValue() == 1) {
			return success();
		} else {
			return fail("更改状态失败");
		}
	}

	/** @Title: CountingScanBarcode 
	 * @Description: 盘点扫码
	 * @author yanggm
	 * @date 2018年9月26日 
	 */
	@Override
	public TransResult CountingScanBarcode(ProCountingDto proCountingDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
//      判断盘点单号是否正确填写
        Resp resp = loadBill(proCountingDto);
        if(Constant.FAIL.equals(resp.getCode())){
        	result.setCode(resp.getCode());
        	result.setMsg(resp.getMsg());
        	return result;
        }
		String LoginName = proCountingDto.getLoginName();
		ProCountingTask proCountingTask = new ProCountingTask();
        proCountingTask.setCountingCode(proCountingDto.getCountingCode());
        proCountingTask.setActiveFlag("1");
        List<ProCountingTask> tmp = proCountingTaskMapper.queryByAny(proCountingTask);

        ProCountingRecords proCountingRecords = new ProCountingRecords();
    	proCountingRecords.setCountingCode(proCountingDto.getCountingCode());
    	proCountingRecords.setBarcode(proCountingDto.getBarcode());
    	proCountingRecords.setActiveFlag("1");
    	//查看这个条码是否已经被盘点了countingCode barcode
    	List<ProCountingRecords> proCountingRecordsList = proCountingRecordsMapper.queryByAny(proCountingRecords);
    	if(proCountingRecordsList.size()>0){
    		result.setCode(Constant.FAIL);
        	result.setMsg("该条码已经被盘点了，请继续扫描");
        	return result;
    	}
//    	if("0".equals(Reason(proCountingDto.getBarcode()))){
//    		result.setCode(Constant.FAIL);
//			result.setMsg("数据异常");
//			return result;
//    	}
    	
//      String contractNo = tmp.get(0).getContractNo();
//      //到rawStorageSn中查询(两种盘点类型)
//      ProStorageSn proStorageSn = new ProStorageSn();
//      if(tmp.get(0).getModelType()!=null||!tmp.get(0).getModelType().equals("")){
//      	//类型盘点
//      	String modelType = tmp.get(0).getModelType();
//      	//根据条码，合同号,类型 到rawStorageSn中查询，判断当前条码是否在合同号下
//      	proStorageSn.setModelType(modelType);
//          proStorageSn.setBarcode(barcode);
//          proStorageSn.setContractNo(contractNo);
//          proStorageSn.setActiveFlag("1");
//      }else{
//      	//合同号盘点
//	        //根据条码，合同号到rawStorageSn中查询，判断当前条码是否在合同号
//	        proStorageSn.setBarcode(barcode);
//	        proStorageSn.setContractNo(contractNo);
//	        proStorageSn.setActiveFlag("1");
//      }
        ProStorageSn proStorageSn = new ProStorageSn();
        proStorageSn.setBarcode(proCountingDto.getBarcode());
        proStorageSn.setModel(tmp.get(0).getModel());
        proStorageSn.setActiveFlag("1");
        List<ProStorageSn> list = proStorageSnMapper.queryByAny(proStorageSn);
        if(list.size()>0){
        	Date now = new Date();
    		//创建盘点记录
    		proCountingRecords.setCountingTime(new Date());
    		proCountingRecords.setModel(list.get(0).getModel());
    		proCountingRecords.setWaCode(list.get(0).getWaCode());
    		proCountingRecords.setWlCode(list.get(0).getWlCode());
    		proCountingRecords.setKeepBy(LoginName);
    		proCountingRecords.setCreateBy(LoginName);
    		proCountingRecords.setGmtCreate(now);
    		proCountingRecords.setLastModifiedBy(LoginName);
    		proCountingRecords.setGmtModified(now);
    		proCountingRecords.setActiveFlag("1");
	    	proCountingRecordsMapper.create(proCountingRecords);
	    	if("2".equals(list.get(0).getBarcodeStatus())){
	    		ProCountingDifference proCountingDifference = new ProCountingDifference();
        		proCountingDifference.setCountingCode(proCountingDto.getCountingCode());
        		proCountingDifference.setCountingTime(now);//盘点时间记录当前时间了
        		proCountingDifference.setProBarcode(proCountingDto.getBarcode());
        		proCountingDifference.setModel(list.get(0).getModel());
        		proCountingDifference.setDifferType("0");//盘盈
//        		proCountingDifference.setUserDefined1(Reason(proCountingDto.getBarcode()));
        		proCountingDifference.setDifferStatus("0");//未处理
        		proCountingDifference.setWaCode(list.get(0).getWaCode());
        		proCountingDifference.setWlCode(list.get(0).getWlCode());
        		proCountingDifference.setKeepBy(LoginName);//保管员记录为当前登录人了
        		proCountingDifference.setGmtCreate(now);
        		proCountingDifference.setActiveFlag("1");
        		proCountingDifference.setCreateBy(LoginName);
        		proCountingDifference.setLastModifiedBy(LoginName);
        		proCountingDifference.setGmtModified(now);
        		proCountingDifferenceMapper.create(proCountingDifference);
	    	}
	    	//返回手持页面信息（当前扫描条码信息）
	        proCountingDto.setModel(list.get(0).getModel());
	        proCountingDto.setWaCode(list.get(0).getWaCode());
	        proCountingDto.setWlCode(list.get(0).getWlCode());
	        proCountingDto.setWeight(list.get(0).getWeight());
//	        proCountingDto.setKeepBy(LoginName);
        } else{
        	ProBarcode proBarcode = new ProBarcode();
        	proBarcode.setBarcode(proCountingDto.getBarcode());
        	proBarcode.setModel(tmp.get(0).getModel());
        	proBarcode.setActiveFlag("1");
        	List<ProBarcode> inLists = proBarcodeMapper.queryByAny(proBarcode);
//        	ProOrderInSn proOrderInSn = new ProOrderInSn();
//        	proOrderInSn.setBarcode(proCountingDto.getBarcode());
//        	proOrderInSn.setModel(tmp.get(0).getModel());
//        	List<ProOrderInSn> inLists = proOrderInSnService.queryList(proOrderInSn);
        	if(inLists.size()>0){
        		Date now = new Date();
	        	proCountingRecords.setCountingTime(new Date());
	        	proCountingRecords.setModel(inLists.get(0).getModel());
	        	proCountingRecords.setKeepBy(LoginName);
	    		proCountingRecords.setCreateBy(LoginName);
	    		proCountingRecords.setGmtCreate(now);
	    		proCountingRecords.setLastModifiedBy(LoginName);
	    		proCountingRecords.setGmtModified(now);
	    		proCountingRecords.setActiveFlag("1");
		    	proCountingRecordsMapper.create(proCountingRecords);
		    	
		    	ProCountingDifference proCountingDifference = new ProCountingDifference();
        		proCountingDifference.setCountingCode(proCountingDto.getCountingCode());
        		proCountingDifference.setCountingTime(now);//盘点时间记录当前时间了
        		proCountingDifference.setProBarcode(proCountingDto.getBarcode());
        		proCountingDifference.setModel(inLists.get(0).getModel());
        		proCountingDifference.setDifferType("0");//盘盈
//        		proCountingDifference.setUserDefined1(Reason(proCountingDto.getBarcode()));
        		proCountingDifference.setDifferStatus("0");//未处理
//        		proCountingDifference.setWlCode(list.get(0).getWlCode());
        		proCountingDifference.setKeepBy(LoginName);//保管员记录为当前登录人了
        		proCountingDifference.setGmtCreate(now);
        		proCountingDifference.setActiveFlag("1");
        		proCountingDifference.setCreateBy(LoginName);
        		proCountingDifference.setLastModifiedBy(LoginName);
        		proCountingDifference.setGmtModified(now);
        		proCountingDifferenceMapper.create(proCountingDifference);
		    	
        		proCountingDto.setModel(inLists.get(0).getModel());
//		        proCountingDto.setKeepBy(LoginName);
        	}
        	else{
        		result.setCode(Constant.FAIL);
//            	result.setMsg("当前条码未下线，请继续扫描");
        		result.setMsg("当前条码不是盘点所需型号");
            	return result;
        	}
        }
        List<ProCountingDto> Countinglist = new ArrayList<>();
        //根据盘点单号在盘点记录表中查询已盘点数量
        ProCountingRecords countingRecords = new ProCountingRecords();
        countingRecords.setCountingCode(proCountingDto.getCountingCode());
        countingRecords.setActiveFlag("1");
        Long nowCountingNum = proCountingRecordsMapper.queryCount(countingRecords);
        proCountingDto.setNowCountingNum(nowCountingNum);
        
        Countinglist.add(proCountingDto);
        result.setList(Countinglist);
		return result;
	}
	
//	/** 
//	* @Title: Reason 
//	* @Description: 盘点差异原因 
//	* @author yanggm 
//	* @date 2018年9月26日
//	* @throws 
//	*/
//	public String Reason(String barcode){
//    	ProHandOutSn handOutSn = new ProHandOutSn();
//    	handOutSn.setBarcode(barcode);
//    	handOutSn.setActiveFlag("1");
//    	Long handOut = proHandOutSnMapper.queryCount(handOutSn);
//    	ProSellOutSn sellOutSn = new ProSellOutSn();
//    	sellOutSn.setBarcode(barcode);
//    	sellOutSn.setActiveFlag("1");
//    	Long sellOut = proSellOutSnMapper.queryCount(sellOutSn);
//    	ProScrapOutSn scrapOutSn = new ProScrapOutSn();
//    	scrapOutSn.setBarcode(barcode);
//    	Long scrapOut = proScrapOutSnMapper.queryCount(scrapOutSn);
//    	
//    	ProOrderInSn orderInSn = new ProOrderInSn();
//    	orderInSn.setBarcode(barcode);
//    	Long in = proOrderInSnMapper.queryCount(orderInSn);
//    	
//    	if(in>0){
//    		if(sellOut>0){return "3";}
//    		if(handOut>0){return "4";}
//    		if(scrapOut>0){return "5";}
//    		return "2";
//    	}
//    	if(sellOut<=0 && handOut<=0 && scrapOut<=0 && in<=0){
//    		return "1";
//    	}
//    	return "0";
//    }

	/** @Title: loadBill 
	 * @Description: 盘点单号判断
	 * @author yanggm
	 * @date 2018年9月26日 
	 */
	@Override
	public Resp loadBill(ProCountingDto proCountingDto) {
		Resp result = new Resp();
    	//Code先置为1SUCCESS
    	result.setCode(Constant.SUCCESS);
    	if (proCountingDto.getCountingCode().equals("")||proCountingDto.getCountingCode()==null){
            result.setCode(Constant.FAIL);
            result.setMsg("请输入盘点单号！");
            return result;
        }
//    	设置查询标志（CountingCode=？ ，ActiveFlag = 1）
        ProCountingTask proCountingTask = new ProCountingTask();
        proCountingTask.setCountingCode(proCountingDto.getCountingCode());
        proCountingTask.setActiveFlag("1");
       
        List<ProCountingTask> tmp = proCountingTaskMapper.queryByAny(proCountingTask);
        if(tmp.size() > 0){
        	if(tmp.get(0).getStauts().equals("0")){
        		result.setMsg("盘点任务存在，请盘点");
        		//记录last_modified_by，gmt_modified	最后修改人，最后修改时间
        		proCountingTask.setLastModifiedBy(proCountingDto.getLoginName());
        		proCountingTask.setGmtModified(new Date());
        		//根据countingTaskId修改
        		proCountingTask.setCountingTaskId(tmp.get(0).getCountingTaskId());
        		//将盘点任务状态置为盘点中
        		Resp resp = updateProCountingTask(proCountingTask);
        		if (Constant.FAIL.equals(resp.getCode())) {
        			result.setCode(resp.getCode());
        			result.setMsg(resp.getMsg());
        		}
        	}else if(tmp.get(0).getStauts().equals("1")){
            	result.setMsg("继续盘点");
        	}else if(tmp.get(0).getStauts().equals("2")){
        		result.setCode(Constant.FAIL);
            	result.setMsg("盘点任务已完成");
        	}else{
        		result.setCode(Constant.FAIL);
        		result.setMsg("盘点任务状态未知!");
        	}
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("盘点任务不存在！");
        }
        return result;
	}

	@Override
	public TransResult complete(ProCountingDto proCountingDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		String LoginName = proCountingDto.getLoginName();
        //根据盘点单号查询
        ProCountingTask countingByCode = new ProCountingTask();
        countingByCode.setCountingCode(proCountingDto.getCountingCode());
        countingByCode.setActiveFlag("1");
        List<ProCountingTask> tmp = proCountingTaskMapper.queryByAny(countingByCode);
        if(tmp.size()>0){
        	proCountingDto.setModel(tmp.get(0).getModel());
        	proCountingDto.setActiveFlag("1");
	        //根据盘点单号，查询盘亏数据
	        List<ProStorageSn> listLose = proStorageSnMapper.queryLose(proCountingDto);
	        if(listLose.size()>0){
	        	//盘亏，存在盘亏数据
	        	for(ProStorageSn proStorageSn:listLose){
	        		//创建盘亏差异记录
	        		ProCountingDifference proCountingDifference = new ProCountingDifference();
//	        		proCountingDifference.setUserDefined1(Reason(proStorageSn.getBarcode()));
	        		proCountingDifference.setCountingCode(proCountingDto.getCountingCode());
	        		proCountingDifference.setCountingTime(new Date());//盘点时间记录当前时间了
	        		proCountingDifference.setProBarcode(proStorageSn.getBarcode());
	        		proCountingDifference.setModel(proStorageSn.getModel());
	        		proCountingDifference.setDifferType("1");//盘亏
	        		proCountingDifference.setDifferStatus("0");//未处理
	        		proCountingDifference.setWaCode(proStorageSn.getWaCode());
	        		proCountingDifference.setWlCode(proStorageSn.getWlCode());
	        		proCountingDifference.setKeepBy(LoginName);//保管员记录为当前登录人了
	        		proCountingDifference.setGmtCreate(new Date());
	        		proCountingDifference.setActiveFlag("1");
	        		proCountingDifference.setCreateBy(LoginName);
	        		proCountingDifference.setLastModifiedBy(LoginName);
	        		proCountingDifference.setGmtModified(new Date());
	        		proCountingDifferenceMapper.create(proCountingDifference);
	        	}
	        }
//	        //根据盘点单号，查询盘盈数据
//	        List<ProCountingRecords> listWin = proCountingRecordsService.queryWin(proCountingDto);
//	        if(listWin.size()>0){
//	        	for(ProCountingRecords proCountingRecords : listWin){
//	        		//创建盘盈差异记录
//	        		ProCountingDifference proCountingDifference = new ProCountingDifference();
//	        		proCountingDifference.setCountingCode(proCountingDto.getCountingCode());
//	        		//proCountingDifference.setPurchaseNo(rawCountingRecords.getPurchaseNo());
//	        		proCountingDifference.setCountingTime(new Date());//盘点时间记录当前时间了
//	        		proCountingDifference.setProBarcode(proCountingRecords.getBarcode());
//	        		proCountingDifference.setModel(proCountingRecords.getModel());
//	        		proCountingDifference.setDifferType("0");//盘盈
//	        		proCountingDifference.setUserDefined1(Reason(proCountingRecords.getBarcode()));
//	        		proCountingDifference.setDifferStatus("0");//未处理
//    				proCountingDifference.setWaCode(proCountingRecords.getWaCode());
//	        		proCountingDifference.setWlCode(proCountingRecords.getWlCode());
//	        		proCountingDifference.setKeepBy(LoginName);//保管员记录为当前登录人了
//	        		proCountingDifference.setGmtCreate(new Date());
//	        		proCountingDifference.setActiveFlag("1");
//	        		proCountingDifference.setCreateBy(LoginName);
//	        		Resp resp = proCountingDifferenceService.create(proCountingDifference);	
//	        		result.setCode(resp.getCode());
//	        		result.setMsg(result.getMsg());
//	        	}
//	        }
	        ProCountingTask proCountingTask = new ProCountingTask();
	        proCountingTask.setLastModifiedBy(LoginName);
	        proCountingTask.setGmtModified(new Date());
			//根据countingTaskId修改
	        proCountingTask.setCountingTaskId(tmp.get(0).getCountingTaskId());

			//将盘点任务状态置为盘点结束
			proCountingTask.setStauts("2");
			Resp respStauts = update(proCountingTask);
//					proCountingTaskMapper.update(proCountingTask);
			ProCountingDifference difference = new ProCountingDifference();
			difference.setCountingCode(proCountingDto.getCountingCode());
			difference.setActiveFlag("1");
			String flag = Constant.SUCCESS;
			if(flag.equals(respStauts.getCode())){
//				if(listWin.size()==0&&listLose.size()==0){
				if(0==proCountingDifferenceMapper.queryCount(difference)){
		        	result.setCode(Constant.SUCCESS);
		        	result.setMsg("盘点无差异");
		        }else if(flag.equals(result.getCode())){
		        	result.setMsg("盘点差异已记录");
		        }
			}else{
				result.setCode(respStauts.getCode());
	        	result.setMsg(respStauts.getMsg());
			}
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("盘点单号不存在");
        }
        return result;
	}
	
}
